import http from '../utils/http.js'

const API_PATHS = {
  GET_WHOLE_PAPER_RESULTS: (paperId) => `/jsonrest/mobile/paper/PaperLabelScore/${paperId}/getWholePaperResults`
}

const STORAGE_KEY = 'checkingLearningStatus:answerDetailsPrefetched'

export const getWholePaperResults = ({ examId, scoreId, paperId, eStatus = 2 } = {}) => {
  if (!examId) throw new Error('[getWholePaperResults] examId不能为空')
  if (!scoreId) throw new Error('[getWholePaperResults] scoreId不能为空')
  if (!paperId) throw new Error('[getWholePaperResults] paperId不能为空')

  return http.get(API_PATHS.GET_WHOLE_PAPER_RESULTS(paperId), {
    exam_id: examId,
    score_id: scoreId,
    e_status: eStatus
  })
}

export const mapWholePaperResults = (response = {}) => {
  const entity = response?.entity || {}
  const resultList = Array.isArray(entity.resultList) ? entity.resultList : []

  const questionSections = resultList.map((section, idx) => ({
    id: section.id || idx,
    title: section.part_name || section.title || `第${idx + 1}部分`,
    questions: Array.isArray(section.questions) ? section.questions : []
  }))

  return {
    raw: entity,
    questionSections
  }
}

export const prefetchAnswerDetails = async ({ examId, scoreId, eStatus = 2, subject, paperId } = {}) => {
  const resolvedPaperId = paperId || subject?.raw?.paper_id || subject?.paper_id
  if (!resolvedPaperId) throw new Error('[prefetchAnswerDetails] paperId不能为空')

  const response = await getWholePaperResults({ examId, scoreId, paperId: resolvedPaperId, eStatus })

  console.log('作答详情-整卷结果:', response)

  // 从缓存中获取考试分析实体数据（包含 exam_name）
  const analysisEntity = uni.getStorageSync('checkingLearningStatus:analysisEntity') || {}

  const payload = {
    examId,
    scoreId,
    eStatus,
    paperId: resolvedPaperId,
    subject,
    response,
    examName: analysisEntity.exam_name || '',
    examTime: analysisEntity.exam_time || ''
  }

  uni.setStorageSync(STORAGE_KEY, payload)
  return payload
}

export const restoreAnswerDetails = () => {
  return uni.getStorageSync(STORAGE_KEY) || null
}

export const clearAnswerDetails = () => {
  uni.removeStorageSync(STORAGE_KEY)
}

export const buildAnswerDetailsViewData = (payload) => {
  if (!payload) return null
  const mapped = mapWholePaperResults(payload.response)
  const entity = payload?.response?.entity || {}
  const questionMap = entity.questionMap || entity.question_map || {}
  const subjectMap = entity.subjectMap || entity.subject_map || {}

  // 构造分区（k_0、k_1...）与 resultList 顺序对应
  const sectionKeys = Object.keys(questionMap)
    .sort((a, b) => {
      const ai = parseInt(String(a).split('_')[1] || '0', 10)
      const bi = parseInt(String(b).split('_')[1] || '0', 10)
      return ai - bi
    })

  const sections = sectionKeys.map((key, index) => {
    const titleLabel = questionMap[key]
    const subjectArray = Array.isArray(subjectMap[key]) ? subjectMap[key] : []
    const count = subjectArray.length
    
    // 根据 subjectMap 数据映射 questions
    const questions = subjectArray.map((item, itemIndex) => {
      const scoreRate = Number(item.score_rate ?? item.scoreRate ?? 0)
      let status = 'wrong'
      if (scoreRate === 1) {
        status = 'correct'
      } else if (scoreRate > 0 && scoreRate < 1) {
        status = 'partial'
      }
      
      return {
        id: item.id || `${key}_${itemIndex}`,
        number: itemIndex + 1,
        status,
        score: item.u_score ?? item.uScore ?? 0,
        totalScore: item.score ?? item.full_score ?? item.fullScore ?? 0,
        sectionKey: key,  // 保存所属分区的 key
        itemIndex: itemIndex  // 保存在分区中的索引
      }
    })
    
    return {
      id: index,
      key,
      titleLabel,
      count,
      questions
    }
  })
  return {
    examId: payload.examId,
    scoreId: payload.scoreId,
    subject: payload.subject,
    questionSections: mapped.questionSections,
    sections,
    examName: payload.examName || '',
    examTime: payload.examTime || ''
  }
}

export const useAnswerDetailsApi = () => ({
  getWholePaperResults,
  mapWholePaperResults,
  prefetchAnswerDetails,
  restoreAnswerDetails,
  clearAnswerDetails,
  buildAnswerDetailsViewData
})

export default {
  getWholePaperResults,
  mapWholePaperResults,
  prefetchAnswerDetails,
  restoreAnswerDetails,
  clearAnswerDetails,
  buildAnswerDetailsViewData,
  useAnswerDetailsApi
}
